//默认App的启动
import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/http/http_utils.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/providers/provider.dart';
import 'package:tender_flutter/router/guards/check_per_guard.dart';
import 'package:tender_flutter/router/guards/login_guard.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/amap_location.dart';
import 'package:tender_flutter/utils/app_update.dart';
import 'package:tender_flutter/utils/jpush_utils.dart';
import 'package:tender_flutter/utils/jpush_verify.dart';
import 'package:tender_flutter/utils/share.dart';
import 'package:tender_flutter/utils/sputils.dart';

class DefaultApp {
  //运行app
  static void run() {
    WidgetsFlutterBinding.ensureInitialized();
    initApp();
    SPUtils.init().then((value) {
      DataManager.instance.cityEntity = SPUtils.getCity();
      DataManager.instance.checkReviewState().then((value) => runApp(Store.init(MyApp())));

    });
  }

  //程序初始化操作
  static Future<void> initApp() async {
    HttpUtils.init(
      baseUrl: ApiPath.baseApi,
    );
    JVerifyUtils.init();
    JPushUtils.init();
    ShareSdkUtils.registerSharePlatform();
    await AMapLocationUtils.init();
    fluwx.registerWxApi(
        appId: AppConfig.wx_key, universalLink: AppConfig.wx_universalLink);
    AppUpdateUtils.init();
  }
}

class MyApp extends StatelessWidget {
  static GlobalKey<NavigatorState> navigatorState = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) {
      // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
      SystemUiOverlayStyle systemUiOverlayStyle =
          SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }

    /// 友好提示页面错误
    ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
      print("错误" + errorDetails.toString());
      return Text("");
    };

    /// 是否是第一次安装
    bool isFirstInstall = SPUtils.getInstallFlag();

    return RefreshConfiguration(
        dragSpeedRatio: 0.91,
        // 头部触发刷新的距离
        headerTriggerDistance: 40,
        headerBuilder: () => ClassicHeader(
              refreshingText: "努力加载中...",
              idleText: "下拉刷新",
              releaseText: "松开刷新",
              completeText: "刷新完成",
              failedText: "刷新失败",
            ),
        footerBuilder: () => ClassicFooter(
              loadingText: "加载中...",
              idleText: "上拉加载",
              noDataText: "没有更多数据啦",
              failedText: "加载失败",
              canLoadingText: "松开开始加载数据", //提示信息
            ),
        child: MaterialApp(
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations
                .delegate, //一定要配置,否则iphone手机长按编辑框有白屏卡着的bug出现
          ],
          supportedLocales: [
            const Locale('zh', 'CN'), //设置语言为中文
          ],
          builder: ExtendedNavigator.builder(
              navigatorKey: navigatorState,
              initialRoute:
                  isFirstInstall ? Routes.splashPage : Routes.mainHomePage,
              router: RouterMap(),
              guards: [LoginGuard(), CheckPermissGurad()],
              builder: (context, extendNav) => GestureDetector(
                  onTap: () {
                    ///点击空白处隐藏键盘
                    FocusScopeNode currentFocus = FocusScope.of(context);
                    if (!currentFocus.hasPrimaryFocus &&
                        currentFocus.focusedChild != null) {
                      FocusManager.instance.primaryFocus.unfocus();
                    }
                  },
                  child: FlutterEasyLoading(child: extendNav))),
          /*控制右上角的debug标签*/
          debugShowCheckedModeBanner: false,
        ));
  }
}
